package com.cbb.display.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cbb.display.config.core.RetResponse;
import com.cbb.display.config.core.RetResult;
import com.cbb.display.dao.UsersMapper;
import com.cbb.display.entity.Users;
import com.cbb.display.enums.ExceptionTypeEnum;
import com.cbb.display.service.UsersService;
import net.bytebuddy.asm.Advice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bigbomb
 * @since 2020-12-26
 */
@RestController
@RequestMapping("/test")
public class UsersController {
    private static final Logger LOG = LoggerFactory.getLogger(UsersController.class);
    @Autowired
    UsersService usersService;
    @Autowired
    UsersMapper usersMapper;

    /**
     * 分页查询操作
     * @return RetResult
     */
    @GetMapping("/list")
    public RetResult listUser(){
        QueryWrapper<Users> query = Wrappers.query();
        query.ge("id", 2);
        //参数一：当前页
        //参数二：页面大小
        Page<Users> page = new Page<>(2, 2);
        IPage<Users> userIPage = usersMapper.selectPage(page, query);

        return RetResponse.makeOKRsp(userIPage);
    }

    /**
     * 新增或者更新用户，更新时id为判断依据
     * @param user
     * @return
     */
    @PostMapping("/save")
    public RetResult saveUser(@Valid @RequestBody Users user){
        try{
            usersService.saveOrUpdate(user);
        }catch (Exception e)
        {
            LOG.error(e.getMessage());
            return RetResponse.makeErrRsp(ExceptionTypeEnum.ERROR.getMessage());
        }

        return RetResponse.makeOKRsp();
    }

    /**
     * 删除某个用户
     * @param id
     * @return
     */
    @PostMapping("/del/{id}")
    public RetResult delUser(@PathVariable Integer id){
        try{
            usersService.removeById(id);
        }catch (Exception e)
        {
            LOG.error(e.getMessage());
            return RetResponse.makeErrRsp(ExceptionTypeEnum.ERROR.getMessage());
        }

        return RetResponse.makeOKRsp();
    }
}
